package com.gcb.xml;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 该类为用DOM解析一个xml文件的示例
 * 
 * @author Cre.Gu
 * 
 */
public class DOMParserXml {

	public static void main(String[] args) {
		try {
			// 创建一个document builder factory
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			// 设置factory 的参数
			// dbf.setValidating( true );
			dbf.setNamespaceAware(true);
			// 从factory 创建一个document builder
			DocumentBuilder db = dbf.newDocumentBuilder();
			// 导入xml 文件, 返回一个DOM Document 对象
			String file = "src/com/gcb/xml/book.xml";
			Document doc = db.parse(file);
			// System.out.println(doc.toString());
			// 遍历DOM Document 对象
			DOMParserXml mdp = new DOMParserXml();
			mdp.traverseTree(doc);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 递归遍历节点. 如果节点为null 则返回 如果节点的类型为DOCUMENT_NODE 则遍历根节点 如果节点的类型为ELEMENT_NODE
	 * 则打印元素名和属性，遍历子节点 如果节点的类型为TEXT_NODE 则打印出来
	 */
	public void traverseTree(Node node) throws Exception {
		if (node == null)
			return;
		int type = node.getNodeType();
		switch (type) {
		case Node.DOCUMENT_NODE:
			Node root = ((Document) node).getDocumentElement();
			traverseTree(root);
			break;

		case Node.ELEMENT_NODE:
			// 打印元素名
			String elementName = node.getNodeName();
			System.out.println(elementName);

			// 打印此元素的所有属性
			NamedNodeMap attrs = node.getAttributes();
			int length = attrs.getLength();
			if (attrs != null && length != 0) {

				System.out.print("attributes: ");
				Node attrNode = null;
				for (int i = 0; i < length; i++) {
					attrNode = attrs.item(i);
					System.out.print(attrNode.getNodeName() + "="
							+ attrNode.getNodeValue().trim() + "\t");
				}
				System.out.println();
			}

			// 遍历子节点
			NodeList childNodes = node.getChildNodes();
			if (childNodes != null) {
				length = childNodes.getLength();
				for (int i = 0; i < length; i++)
					traverseTree(childNodes.item(i));
			}
			break;

		case Node.TEXT_NODE:
			String text = node.getNodeValue().trim();
			System.out.println(text);
		}
	}
}